<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;
use app\traits\MyModelTrait;

/**
 * @mixin \think\Model
 */
class AdminUser extends Model
{
    use MyModelTrait;

    // 管理员
    protected $table = "admin_user";

    // table.fields
    const FIELDS = [
        // admin_user.is_lock
        'is_lock' => [0 => '否', 1 => '是'],
        // admin_user.is_deleted
        'is_deleted' => [0 => '否', 1 => '是'],
    ];

    /**
     * 生成记录
     *
     * @param string $account   账户
     * @param string $password  密码
     * @param string $salt      加密盐
     * @param string $nickname  昵称
     * @param int    $is_lock   锁定
     */
    public static function generateLog(string $account, string $password, string $salt, string $nickname = '', int $is_lock = 0): void
    {
        $insert = [
            'account'       => $account,
            'password'      => $password,
            'salt'          => $salt,
            'nickname'      => $nickname,
            'is_lock'       => $is_lock,
            'is_deleted'    => 0,
            'admin_role_id' => 0,
            'created_at'    => date('Y-m-d H:i:s'),
            'updated_at'    => date('Y-m-d H:i:s'),
        ];
        self::insert($insert);
    }// generateLog() end

    /**
     * update admin_user.password
     *
     * @param string $account       admin_user.account
     * @param string $password      密码明文
     * @param string $salt
     */
    public static function setPassword(string $account, string $password, string $salt): void
    {
        $res = self::whereRaw('account = :account', ['account' => $account])->findOrEmpty();
        if ($res->isEmpty()) return;
        $res->password = self::generatePassword($password, $salt);
        $res->save();
    }// setPassword() end

    /**
     * 账号是否存在
     *
     * @param string $account   admin_user.account
     * @return bool true-存在
     */
    public static function hasAccount(string $account): bool
    {
        $admin = self::whereRaw('account = :account', ['account' => $account])->findOrEmpty();
        return $admin->isExists();
    }// hasAccount() end

    /**
     * 是否是超级管理员
     *
     * @param string $account   admin_user.account
     * @return bool true-是
     */
    public static function isSuperAdmin(string $account = ''): bool
    {
        // config/super_admin.php 配置文件里的账户
        return in_array($account, config('super_admin'));
    }// isSuperAdmin() end

    /**
     * 获取 token key
     *
     * @param int $admin_user_id
     * @return string
     */
    public static function getTokenKey(int $admin_user_id): string
    {
        return "admin_user.token_{$admin_user_id}";
    }// getTokenKey() end
}
